﻿#if UNITY_EDITOR
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

public class ReferenceGroupHierarchyEditor
{
    static List<Color> unitColors;

    [InitializeOnLoadMethod]
    private static void Init()
    {
        unitColors = new List<Color>();
        unitColors.Add(new Color(1, 0, 0));
        unitColors.Add(new Color(1, 0, 1));
        unitColors.Add(new Color(0, 1, 1));
        unitColors.Add(new Color(0, 1, 0));
        unitColors.Add(new Color(0, 0, 1));

        EditorApplication.hierarchyWindowItemOnGUI -= OnHierarchyWindowItemOnGUI;
        EditorApplication.hierarchyWindowItemOnGUI += OnHierarchyWindowItemOnGUI;
    }

    static void OnHierarchyWindowItemOnGUI(int instanceID, Rect selectionRect)
    {
        var obj = EditorUtility.InstanceIDToObject(instanceID) as GameObject;

        if (obj == null)
            return;

        if(obj.GetComponent<ReferenceGroup>() != null)
        {
            var gs = obj.GetComponentsInParent<ReferenceGroup>();

            if (gs.Length == 0)
                return;

            Color color = unitColors[(gs.Length - 1) % unitColors.Count];
            GUIStyle style = new GUIStyle()
            {
                padding = { left = EditorStyles.label.padding.left - 36, top = EditorStyles.label.padding.top + 3 },
                normal = { textColor = color },
                fontSize = 8
            };

            GUI.Label(selectionRect, "=RG=", style);

            return;
        }

        if (obj.GetComponent<ReferenceUnit>() != null)
        {
            var gs = obj.GetComponentsInParent<ReferenceGroup>();
            Color color = unitColors[gs.Length % unitColors.Count];
            GUIStyle style = new GUIStyle()
            {
                padding = { left = EditorStyles.label.padding.left - 35, top = EditorStyles.label.padding.top + 3 },
                normal = { textColor = color },
                fontSize = 8
            };

            GUI.Label(selectionRect, "-RU-", style);
        }
    }
}

#endif